package com.lau.security;

import com.lau.common.enums.ResultStatusEnum;
import com.lau.common.exception.DebugException;
import com.lau.constant.CacheConstants;
import com.lau.service.SysUserService;
import com.lau.utils.JwtUtils;
import com.lau.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    JwtUtils jwtUtils;

    RedisUtil redisUtil;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager,JwtUtils jwtUtils,RedisUtil redisUtil) {
        super(authenticationManager);
        this.jwtUtils = jwtUtils;
        this.redisUtil = redisUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        LoginUser loginUser = getLoginUser(request);
        if (loginUser == null) {
            chain.doFilter(request, response);
            return;
        }
        jwtUtils.verifyToken(loginUser);
        UsernamePasswordAuthenticationToken token
                = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        //将给定的身份验证令牌设置到当前线程的安全上下文中。
        SecurityContextHolder.getContext().setAuthentication(token);
        chain.doFilter(request, response);
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = request.getHeader(jwtUtils.getHeader());
        if (StringUtils.isNotBlank(token)) {
            Claims claims = jwtUtils.getClaimByToken(token);
            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get(CacheConstants.LOGIN_USER_KEY);
            String userKey = jwtUtils.getTokenKey(uuid);
            Object o = redisUtil.get(userKey);
            if (o == null) {
                throw new DebugException(ResultStatusEnum.LOGIN_OUT);
            }
            return (LoginUser) o;
        }
        return null;
    }
}
